<!-- components/Pagination/Pagination.vue -->
<template>
  <div class="pagination" :class="{ disabled }" role="navigation">
    <!-- 分页内容 -->
    <div v-for="item in layoutArray" :key="item">
      <!-- 首页 -->
      <button
          v-if="item === 'first'"
          class="pagination-first"
          :disabled="isFirstDisabled"
          @click="handleFirst"
          aria-label="首页"
      >
        {{ firstText }}
      </button>

      <!-- 上一页 -->
      <button
          v-if="item === 'prev'"
          class="pagination-prev"
          :disabled="isPrevDisabled"
          @click="handlePrev"
          :aria-label="prevText"
      >
        {{ prevText }}
      </button>

      <!-- 页码 -->
      <template v-if="item === 'pager'">
        <button
            v-for="page in pagerRange"
            :key="page"
            class="pagination-item"
            :class="{ active: current === page }"
            :disabled="disabled"
            @click="handlePage(page)"
            :aria-label="`第 ${page} 页`"
        >
          {{ page }}
        </button>
      </template>

      <!-- 下一页 -->
      <button
          v-if="item === 'next'"
          class="pagination-next"
          :disabled="isNextDisabled"
          @click="handleNext"
          :aria-label="nextText"
      >
        {{ nextText }}
      </button>

      <!-- 尾页 -->
      <button
          v-if="item === 'last'"
          class="pagination-last"
          :disabled="isLastDisabled"
          @click="handleLast"
          aria-label="尾页"
      >
        {{ lastText }}
      </button>

      <!-- 分页大小 -->
      <select
          v-if="item === 'sizes'"
          class="pagination-sizes"
          :value="internalPageSize"
          @change="handleSizeChange"
          :disabled="disabled"
      >
        <option v-for="size in [10, 20, 30, 50]" :key="size" :value="size">
          {{ size }}条/页
        </option>
      </select>
    </div>
  </div>
</template>

<script setup>
import { computed, watch, ref } from 'vue'

const props = defineProps({
  // 分页数据相关
  currentPage: {
    type: Number,
    default: 1,
    validator: value => value > 0
  },
  pageSize: {
    type: Number,
    default: 10,
    validator: value => value > 0
  },
  total: {
    type: Number,
    default: 0,
    validator: value => value >= 0
  },
  pageCount: {
    type: Number,
    default: null
  },

  // 分页样式相关
  layout: {
    type: String,
    default: 'prev, pager, next'
  },
  pagerCount: {
    type: Number,
    default: 5,
    validator: value => value % 2 === 1 && value >= 3
  },
  disabled: Boolean,

  // 语言相关
  prevText: { type: String, default: '上一页' },
  nextText: { type: String, default: '下一页' },
  firstText: { type: String, default: '首页' },
  lastText: { type: String, default: '尾页' }
})

const emit = defineEmits(['update:currentPage', 'update:pageSize', 'change', 'size-change'])

const internalCurrent = ref(props.currentPage)
const internalPageSize = ref(props.pageSize)

// 计算总页数
const totalPage = computed(() => {
  if (props.pageCount !== null) return props.pageCount
  return Math.ceil(props.total / internalPageSize.value) || 1
})

// 生成页码范围
const pagerRange = computed(() => {
  const current = internalCurrent.value
  const pageCount = totalPage.value
  const pagerCount = props.pagerCount
  const half = Math.floor(pagerCount / 2)

  let start = current - half
  let end = current + half

  if (start < 1) {
    end += 1 - start
    start = 1
  }
  if (end > pageCount) {
    start -= end - pageCount
    end = pageCount
  }

  start = Math.max(start, 1)
  end = Math.min(end, pageCount)

  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

// 布局处理
const layoutArray = computed(() => props.layout.replace(/\s+/g, '').split(','))

// 按钮禁用状态
const isFirstDisabled = computed(() => internalCurrent.value === 1 || props.disabled)
const isLastDisabled = computed(() => internalCurrent.value === totalPage.value || props.disabled)
const isPrevDisabled = computed(() => internalCurrent.value === 1 || props.disabled)
const isNextDisabled = computed(() => internalCurrent.value === totalPage.value || props.disabled)

// 事件处理
const handlePage = (page) => {
  if (page === internalCurrent.value || props.disabled) return
  internalCurrent.value = page
  emitChange()
}

const handlePrev = () => handlePage(internalCurrent.value - 1)
const handleNext = () => handlePage(internalCurrent.value + 1)
const handleFirst = () => handlePage(1)
const handleLast = () => handlePage(totalPage.value)

const handleSizeChange = (e) => {
  const newSize = Number(e.target.value)
  internalPageSize.value = newSize
  internalCurrent.value = 1
  emit('update:pageSize', newSize)
  emit('size-change', newSize)
  emit('change', 1)
}

const emitChange = () => {
  emit('update:currentPage', internalCurrent.value)
  emit('change', internalCurrent.value)
}

// 同步外部currentPage变化
watch(() => props.currentPage, (val) => {
  if (val !== internalCurrent.value) {
    internalCurrent.value = Math.min(Math.max(1, val), totalPage.value)
  }
})

// 错误处理
watch([() => props.total, () => props.pageSize], () => {
  if (props.pageCount === null && props.total < 0) {
    console.warn('[Pagination] total 不能为负数')
  }
})
</script>

<style scoped>
.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
  user-select: none;
}

.pagination button {
  padding: 4px 12px;
  border: 1px solid #ddd;
  background: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:hover:not(:disabled) {
  background: #f5f5f5;
}

.pagination button.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.pagination-sizes {
  padding: 4px;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .pagination {
    flex-wrap: wrap;
  }

  .pagination-item:not(.active) {
    display: none;
  }
}
</style>